package com.xoa.service.infomation;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.infomation.InformationMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.infomation.Information;
import com.xoa.model.users.Users;
import com.xoa.service.users.UsersService;
import com.xoa.util.ExcelUtil;
import com.xoa.util.FileUploadUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xoa.util.FileUploadUtil.allowUpload;

/**
 * Created by liuqian on 2017/12/25.
 */
@Service
public class InformationService {

    @Resource
    private InformationMapper informationMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private DepartmentMapper departmentMapper;

    @Autowired
    private UsersService usersService;


    public  ToJson<Information> insertInfo(Information information, HttpServletRequest request){
       ToJson<Information> toJson =new ToJson<Information>(1,"err");
        try {
            int count=informationMapper.insertSelective(information);
            if(count>0){
                toJson.setObject(information);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月25日 下午12:32:00
     * 方法介绍:   查看新建列表
     * 参数说明:
     * 返回值说明:
     */
    public ToJson<Information> getInformationList(HttpServletRequest request,Integer page,Integer pageSize,Boolean useFlag,Information informatione){
       ToJson<Information> json =new ToJson<Information>(1,"err");
        //分页处理
        //从session中获取当前登录人的信息
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("userId",users.getUserId()); //填报人
        map.put("deliveryDeptId",users.getUserId()); //报送人
        map.put("iscollection",informatione.getIscollection()); //是否采集1是，0否
        try {
            List<Information> informations = informationMapper.selectInformationList(map);
            for(Information information:informations){

                information.setDeliveryDeptName(usersService.getUserNameById(information.getDeliveryDeptId()));

                //处理部门和人
                String deptIds = information.getDeptId();
                if(!StringUtils.checkNull(deptIds)){
                    String substring = deptIds.substring(0, deptIds.length() - 1);
                    String deptNameById = departmentMapper.getDeptNameById(Integer.valueOf(substring));
                    information.setDeptName(deptNameById);
                }
                String userIds = information.getUserId();
                if(!StringUtils.checkNull(userIds)){
                    String substring = userIds.substring(0, userIds.length() - 1);
                    Users usersByuserId = usersMapper.getUsersByuserId(substring);
                    if(usersByuserId!=null){
                        information.setUserName(usersByuserId.getUserName());
                    }
                }
                //获取每条推送人的userId
                String userId = information.getUserId();
                String rightuserId=userId.substring(0,userId.length()-1);
                //获取转交标识
                String publish = information.getPublish();
                if(publish.equals("0")){
                if(!StringUtils.checkNull(userId)){
                    if(users.getUserId().equals(rightuserId)){
                        information.setSign("1");
                    }
                    Users usersByuserId = usersMapper.getUsersByuserId(users.getUserId());
                    Map<String,Object> paraMap= new HashedMap();
                    String deptId1 = information.getDeptId();
                    paraMap.put("deptId",deptId1.substring(0,deptId1.length()-1));
                    paraMap.put("userId",users.getUserId());
                    int i = informationMapper.selectPersonCount(paraMap);
                   if(i>0){
                       information.setSign("1");
                   }
                }
                }
            }
            json.setMsg("ok");
            json.setFlag(0);
            json.setObj(informations);
            json.setTotleNum(pageParams.getTotal());
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月25日 下午16:32:00
     * 方法介绍:   查看新建列表详情
     * 参数说明:
     * 返回值说明:
     */
    public ToJson<Information> getInformationDetail(HttpServletRequest request,Integer id){
        ToJson<Information> json =new ToJson<Information>(1,"err");
        try {
            Information information = informationMapper.selectByPrimaryKey(id);
            String deliveryDeptId = information.getDeliveryDeptId();
            if(!StringUtils.checkNull(deliveryDeptId)){
                information.setDeliveryDeptName(usersService.getUserNameById(deliveryDeptId));
            }
                String deptId = information.getDeptId();
                if(!StringUtils.checkNull(deptId)){
                    String substring = deptId.substring(0, deptId.length() - 1);
                    String deptNameById = departmentMapper.getDeptNameById(Integer.valueOf(substring));
                    information.setDeptName(deptNameById);
                }
                String userId = information.getUserId();
                if(!StringUtils.checkNull(userId)){
                    String substring = userId.substring(0, userId.length() - 1);
                    Users usersByuserId = usersMapper.getUsersByuserId(substring);
                    if(usersByuserId!=null){
                        information.setUserName(usersByuserId.getUserName());
                    }
                }
                if(!StringUtils.checkNull(information.getManagerId())){
                    String[] split = information.getManagerId().split(",");
                    StringBuffer sb =new StringBuffer();
                    List<Users> userByUserIds = usersMapper.getUserByUserIds(split);
                    for(Users users:userByUserIds){
                        sb.append(users.getUserName()+",");
                    }
                    String str =sb.toString().substring(0,sb.toString().length()-1);
                    information.setManagerName(str);
                }
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(information.getAttachmentName()!=null&&!"".equals(information.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(information.getAttachmentName(),information.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_INFORMATION);
            }
            //图片附件处理
            List<Attachment> imgattachmentList=new ArrayList<Attachment>();
            if(information.getAttachmentName2()!=null&&!"".equals(information.getAttachmentName2())){
                imgattachmentList= GetAttachmentListUtil.returnAttachment(information.getAttachmentName2(),information.getAttachmentId2(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_INFORMATION_IMG);
            }
            information.setAttachmentList(attachmentList);
            information.setImgattachments(imgattachmentList);
            json.setMsg("ok");
            json.setFlag(0);
            json.setObject(information);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }

        return json;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月25日 下午17:32:00
     * 方法介绍:   修改报送信息
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Object> editInformation(HttpServletRequest request,Information information){
        ToJson<Object> json =new ToJson<Object>(1,"err");
        try {
            int i = informationMapper.updateByPrimaryKeySelective(information);
            if(i>0){
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }

        return  json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月25日 下午17:32:00
     * 方法介绍:   删除单条信息
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Object> deleteInfomationById(Integer id){
        ToJson<Object> json =new ToJson<Object>(1,"err");
        try {
            int i = informationMapper.deleteByPrimaryKey(id);
            if(i>0){
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月25日 下午17:32:00
     * 方法介绍:   获取用户当前用户信息和当前时间
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Object> getUsersInfo(HttpServletRequest request){
        ToJson<Object> json =new ToJson<Object>();
        try {
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            Date date =new Date();
            long time = date.getTime();
            SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            Map<String,Object> map =new HashedMap();
            map.put("userId",users.getUserId());
            map.put("userName",users.getUserName());
            map.put("deptId",users.getDeptId());
            Department deptById = departmentMapper.getDeptById(users.getDeptId());
            map.put("deptName",deptById.getDeptName());
            map.put("createTime",format);
            json.setObject(map);
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月25日 下午17:32:00
     * 方法介绍:   报送处理列表查询
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Information> getHandleList(HttpServletRequest request, Integer page, Integer pageSize, Boolean useFlag, Information information){
    ToJson<Information> json =new ToJson<Information>(1,"err");
    Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("managerId",users.getUserId()); //审批人
        map.put("deptId",information.getDeptId()); //部门
        map.put("isread",information.getIsread()); //是否阅读
        try {
            List<Information> information1 = informationMapper.selectHandleList(map);
            for(Information info:information1){
                //报送人Name
                info.setDeliveryDeptName(usersService.getUserNameById(info.getDeliveryDeptId()));
                String deptId = info.getDeptId();
                if(!StringUtils.checkNull(deptId)){
                    String substring = deptId.substring(0, deptId.length() - 1);
                    String deptNameById = departmentMapper.getDeptNameById(Integer.valueOf(substring));
                    info.setDeptName(deptNameById);
                }
                String userId = info.getUserId();
                if(!StringUtils.checkNull(userId)){
                    String substring = userId.substring(0, userId.length() - 1);
                    Users usersByuserId = usersMapper.getUsersByuserId(substring);
                    if(usersByuserId!=null){
                        info.setUserName(usersByuserId.getUserName());
                    }
                }
            }
            json.setMsg("ok");
            json.setFlag(0);
            json.setObj(information1);
            json.setTotleNum(pageParams.getTotal());
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月26日 上午10:32:00
     * 方法介绍:   报送查询与导出接口
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Information> queryInfoList(HttpServletRequest request, Information information,String deptIds,String userIds,String startTime,String endTime,HttpServletResponse response,Integer page,Integer pageSize,Boolean useFlag,String export){
        ToJson<Information> json =new ToJson<Information>();
        try {
            Map<String,Object> map =new HashedMap();
            //分页处理
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            if(information!=null){
                map.put("title",information.getTitle());
                map.put("iscollection",information.getIscollection());
            }
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            if(!StringUtils.checkNull(deptIds)){
                map.put("deptIds",deptIds.substring(0,deptIds.length()-1));
            }
            if(!StringUtils.checkNull(userIds)){
                map.put("userIds",userIds.substring(0,userIds.length()-1));
            }
         /*   if(!StringUtils.checkNull(deptIds)){
                String[] split = deptIds.split(",");
                map.put("deptIds",split);
            }
            if(!StringUtils.checkNull(userIds)){
                String[] split = userIds.split(",");
                map.put("userIds",split);
            }*/
            Users sessionInfo = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            //如果是这督查信息科、文明办-文化站、宣传部三个科室中的一个，择可以查询全部的报送信息，否则择只能查看自己科室的信息
            int i1 = informationMapper.selectCountByUserId(sessionInfo.getUserId());
            if(i1<=0){
                map.put("deptId",sessionInfo.getDeptId());
            }
            List<Information> information1 = informationMapper.queryInfoList(map);
            for(Information info:information1){
                String deptId = info.getDeptId();
                if(!StringUtils.checkNull(deptId)){
                    String substring = deptId.substring(0, deptId.length() - 1);
                    String deptNameById = departmentMapper.getDeptNameById(Integer.valueOf(substring));
                    info.setDeptName(deptNameById);
                }
                String userId = info.getUserId();
                if(!StringUtils.checkNull(userId)){
                    String substring = userId.substring(0, userId.length() - 1);
                    Users usersByuserId = usersMapper.getUsersByuserId(substring);
                    if(usersByuserId!=null){
                        info.setUserName(usersByuserId.getUserName());
                    }
                }
            }
            //1是查询
            if(("1").equals(export)){
                json.setMsg("ok");
                json.setObj(information1);
                json.setFlag(0);
                json.setTotleNum(pageParams.getTotal());
            }
           else{
                //添加序号列
                int i=1;
                for(Information in:information1){
                    //时间处理
                    SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = simpleDateFormat.format(in.getCreateTime());
                    in.setExportDateTime(format);
                    in.setSid(i);
                    i++;
                    if(in.getIsread().equals("0")){
                        in.setIsreadName("否");
                    }else{
                        in.setIsreadName("是");
                    }
                    if(in.getIscollection().equals("0")){
                        in.setIscollectionName("否");
                    }
                    else{
                        in.setIscollectionName("是");
                    }

                }

                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("信息报送导出表", 9);
                String[] secondTitles = {"序号", "填报部门", "填报人","填报时间","标题","是否采集","是否阅读"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

                // String[] beanProperty = {user.getDep().getDeptName(),"userName","userPrivName", "roleAuxiliaryName","online","sex","online","telNoDept","telNoDept","departmentPhone","email"};
                String[] beanProperty = {"sid", "deptName", "userName","exportDateTime","title","iscollectionName","isreadName"};

                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, information1, beanProperty);
                ServletOutputStream out = response.getOutputStream();

                String filename = "信息报送导出表.xls";
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月26日 上午10:32:00
     * 方法介绍:   更新采集/是否阅读
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Object> updateState(Information information){
        ToJson<Object> json =new ToJson<Object>(1,"err");
        try {
            int i = informationMapper.updateState(information);
          if(i>0){
              json.setFlag(0);
              json.setMsg("ok");
          }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月26日 上午10:32:00
     * 方法介绍:   统计分析图接口
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Object> getstaticInfo(String year){
        ToJson<Object> json =new ToJson<Object>(1,"err");
        try {
            int sum=0;
            Map<String,Object> map =new HashedMap();
                Map<String,Object> paramap1 =new HashedMap();
       /*     Map<String,Object> paramap2 =new HashedMap();
            Map<String,Object> paramap3 =new HashedMap();
            Map<String,Object> paramap4 =new HashedMap();
            Map<String,Object> paramap5 =new HashedMap();
            Map<String,Object> paramap6 =new HashedMap();
            Map<String,Object> paramap7 =new HashedMap();
            Map<String,Object> paramap8 =new HashedMap();
            Map<String,Object> paramap9 =new HashedMap();
            Map<String,Object> paramap10 =new HashedMap();
            Map<String,Object> paramap11 =new HashedMap();
            Map<String,Object> paramap12 =new HashedMap();*/
            for(int i=1;i<=12;i++){
             paramap1.put("year",year);
             paramap1.put("month",i);
                int  getcount= informationMapper.getcount(paramap1);
                sum+=getcount;
                if(i==1){
                    map.put("one",getcount);
                }
                if(i==2){
                    map.put("two",getcount);
                }
                if(i==3){
                    map.put("three",getcount);
                }
                if(i==4){
                    map.put("four",getcount);
                }
                if(i==5){
                    map.put("five",getcount);
                }
                if(i==6){
                    map.put("six",getcount);
                }
                if(i==7){
                    map.put("seven",getcount);
                }
                if(i==8){
                    map.put("eight",getcount);
                }
                if(i==9){
                    map.put("nine",getcount);
                }
                if(i==10){
                    map.put("ten",getcount);
                }
                if(i==11){
                    map.put("eleven",getcount);
                }
                if(i==12){
                    map.put("twelve",getcount);
                }
            }
        /*    paramap1.put("year",year);
            paramap1.put("month",1);
            paramap2.put("year",year);
            paramap2.put("month",2);
            paramap3.put("year",year);
            paramap3.put("month",3);
            paramap4.put("year",year);
            paramap4.put("month",4);
            paramap5.put("year",year);
            paramap5.put("month",5);
            paramap6.put("year",year);
            paramap6.put("month",6);
            paramap7.put("year",year);
            paramap7.put("month",7);
            paramap8.put("year",year);
            paramap8.put("month",8);
            paramap9.put("year",year);
            paramap9.put("month",9);
            paramap10.put("year",year);
            paramap10.put("month",10);
            paramap11.put("year",year);
            paramap11.put("month",11);
            paramap12.put("year",year);
            paramap12.put("month",12);*/
            map.put("count",sum);
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 图片上传
     * @param request
     * @param imageFile
     */
    public int uploadImg(Information information,MultipartFile imageFile,HttpServletRequest request){
        int resultFlag=0;
        try{
            //图片进行处理
            if(imageFile!=null){
                String imageType=imageFile.getContentType();
                boolean b = allowUpload(imageType);
                if (!b){
                    resultFlag=1;//固定资源图片格式不正确
                }
            }
            String realPath = request.getSession().getServletContext().getRealPath("/");
            String resourcePath = "ui/img/information";
            //先查询是否已经上传了该图片，如果上传了删除后再上传，否则直接上传
             Information temp=informationMapper.selectObjectById(information.getId());
            if(temp!=null){
                if (!StringUtils.checkNull(temp.getImage())) {//上传图片
                    File temp1 = new File(realPath + resourcePath + temp.getImage());
                    if (temp1.exists()) {
                        temp1.delete();
                    }
                }
            }
            //上传图片并进行修改数据库数据
            if (imageFile != null) {
                if (allowUpload(imageFile.getContentType())) {
                    String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());
                    File dir = new File(realPath + resourcePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File file = new File(dir, fileName);
                    imageFile.transferTo(file);
                    information.setImage(fileName);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultFlag;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017年12月26日 上午10:32:00
     * 方法介绍:   查询科室数量
     * 参数说明:   Information information
     * 返回值说明:
     */
    public ToJson<Information> getDeptInfo(HttpServletRequest request,String year){
        ToJson<Information> json =new ToJson<Information>();
        int sum=0;
        try {
            List<Information> returnList =new ArrayList<Information>();
            List<Information> information = informationMapper.selectdeptCount(year);
            for(Information in:information){
                Integer deptTypeCount = in.getDeptTypeCount();
                if(deptTypeCount>0){
                    returnList.add(in);
                }
                sum+=deptTypeCount;
            }
            json.setMsg("ok");
            json.setObj(returnList);
            json.setTotleNum(sum);
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
            e.printStackTrace();
        }
        return json;
    }
}
